package org.interactive.spring.intro.controller.mvc;

import org.interactive.spring.intro.exceptions.ValidationException;
import org.interactive.spring.intro.service.UsersService;
import org.interactive.spring.intro.transport.UserTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * FormHandlingController class
 *
 * @author bogdan.solga
 *
 * Date: 12.06.2013, time: 16:06
 */
@Controller
@RequestMapping("/form")
public class FormHandlingController {

    private static final String USERS_PAGE_URI = "redirect:/spring-intro/mvc/users";

    private static final String CREATE_USER_PAGE_NAME = "createUser";

    @Autowired
    private UsersService usersService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveUser(@ModelAttribute UserTO user) throws ValidationException {
        usersService.save(user);

        return USERS_PAGE_URI;
    }

    @RequestMapping(value = "/load", method = RequestMethod.GET)
    public String loadForm(Model model) {
        model.addAttribute("user", new UserTO());

        return CREATE_USER_PAGE_NAME;
    }
}
